import React, { useContext, useState } from 'react';
import { AutoComplete, Card, Empty, Input, Spin, Tree, TreeProps } from 'antd';
import { clickScrollToAnchor, getTenantID, loopArray, searchChangeColor, transltateFn } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { SearchOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import pageStyles from '@/common/pageLayout.less';
import { AssetAcquisitionManageAPI } from '../common/type';

export const OpenMaterialType: React.FC<AssetAcquisitionManageAPI.IOpenMaterialType> = ({
  typeTreeLoading,
  typeTreeData,
  onSelect,
  onTreeKey: { selectKeys, setSelectKeys },
  loadMdicMapObj,
}) => {
  /** 获取上下文 */
  const styleFixCls = 'contract-styfixcls-';

  /** 左侧类型树搜索 */
  const [typeTreeSearchObj, setTypeTreeSearchObj] = useState<Record<string, any>>({
    searchValue: '',
    expandedKeys: [],
  });

  /**
   * tree组件选中事件
   * */
  const onSelectTree: TreeProps['onSelect'] = (selectedKeys) => {
    if (selectedKeys?.length) {
      setSelectKeys(selectedKeys);
      onSelect(selectedKeys?.toString());
    } else {
      onSelect(null);
      setSelectKeys(selectedKeys);
    }
  };

  /** 处理树数据 */
  const handleLeftTree = (treeList: Record<string, any>[]) => {
    return treeList?.map((item) => {
      return {
        ...item,
        title: (
          <div id={item?.id + 'contractMaterialType'} className={pageStyles['over-flow-hidden']}>
            {item.storeName}
          </div>
        ),
        key: item?.id,
        children: item?.childs?.length > 0 ? handleLeftTree(item?.childs) : [],
      };
    });
  };

  /** 树展开方法 */
  const onTreeExpand = (e: any) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      expandedKeys: e,
    });
  };

  /** 搜索下拉菜单 */
  const autoOptionLeft = (dataList: Record<string, any>[]) => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item: any) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if (!typeTreeSearchObj?.searchValue) {
          option.push({
            value: item?.name,
            key: item?.id,
            itemrowobj: { ...item },
          });
        } else if (item?.name?.includes(typeTreeSearchObj?.searchValue)) {
          option.push({
            value: item?.name,
            key: item?.id,
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(dataList);
    return option;
  };

  /** 自动完成组件的事件 */
  const onAutoSelectLeft = (value: string, option: any) => {
    const optionId = option?.key;
    const rowObj = option?.itemrowobj;
    const targetNode = loopArray(typeTreeData);

    let openTreeIds = transltateFn(targetNode, rowObj?.pID);
    const searchObj: Record<string, any> = {
      searchValue: value,
      expandedKeys: openTreeIds,
    };

    setTypeTreeSearchObj(searchObj);
    setSelectKeys([optionId]);

    onSelect(optionId);

    setTimeout(() => {
      clickScrollToAnchor(optionId + 'contractMaterialType');
    }, 1000);
  };

  /** 搜索框的事件 */
  const onInputChange = (ev: Record<string, any>) => {
    setTypeTreeSearchObj({
      ...typeTreeSearchObj,
      searchValue: ev?.target?.value,
    });
  };

  return (
    <Card
      className={`${styleFixCls}materialModal-materialTypeTree`}
      bodyStyle={{ padding: '5px 0px' }}
      title={
        <>
          <AutoComplete
            style={{ width: '100%' }}
            options={autoOptionLeft(typeTreeData)}
            notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            onSelect={onAutoSelectLeft}
          >
            <Input placeholder="请按类型名称搜索" suffix={<SearchOutlined />} onChange={onInputChange} value={typeTreeSearchObj?.searchValue || ''} />
          </AutoComplete>
        </>
      }
    >
      <Spin spinning={typeTreeLoading}>
        <ScrollBarLayout>
          {typeTreeData?.length === 0 ? (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          ) : (
            <Tree
              onSelect={onSelectTree}
              blockNode={true}
              treeData={handleLeftTree(typeTreeData)}
              selectedKeys={selectKeys}
              expandedKeys={typeTreeSearchObj?.expandedKeys}
              defaultExpandParent={true}
              onExpand={onTreeExpand}
            />
          )}
        </ScrollBarLayout>
      </Spin>
    </Card>
  );
};
